<template>
    <el-card v-show="visible" shadow="always" class="aui-card--fill" :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false" >
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm"   @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'" style="width:80%;">


      <el-row>
        <el-col :span="12">
          <el-form-item label="套餐名称" prop="name" >
            <el-input v-model="dataForm.name" placeholder="套餐名称" style="width: 80%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="套餐分类" prop="categoryId">
            <el-select v-model="dataForm.categoryId"  placeholder="请选择套餐分类">
              <el-option v-for="(item,index) in categoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="套餐价格" prop="price">
            <el-input v-model="dataForm.price" placeholder="套餐价格"  style="width: 80%"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="编码" prop="code">
            <el-input v-model="dataForm.code" placeholder="编码"  style="width: 80%"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="套餐菜品" prop="name" >
<!--        <el-input v-model="dataForm.setmealDishes" placeholder="套餐名称" style="width: 80%"></el-input>-->
        <div style="border:1px solid 	#A9A9A9;">
            <span> <el-button @click="dialogVisible=true" type="success"   icon="el-icon-plus"   round>添加菜品</el-button></span>

          <setmeal-dish spread="false" v-if=""  @refreshDataList="getDataList" class="addAndUpdate"></setmeal-dishv>

        </div>
      </el-form-item>

      <el-form-item label="菜品图片" prop="image">
        <el-upload
            class="avatar-uploader"
            :action="url"
            ref="upload"
            :show-file-list="false"
            :before-upload="beforeUploadHandle"
            :on-success="successHandle"
            :on-change="onChange"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" v-model="imageUrl">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

          <el-form-item label="描述信息" prop="description">
          <el-input v-model="dataForm.description" placeholder="描述信息" type="textarea"></el-input>
      </el-form-item>


      <el-form-item :label="$t('updateStatus')" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">{{$t('updateStatusBatch')}}</el-radio>
          <el-radio :label="0">{{ $t('updateStatusBatch_stop') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <div class="btn-box">
        <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
      </div>
      </el-form>
      <el-dialog
          :title="!$t('add') +'菜品' " :close-on-click-modal="false" :close-on-press-escape="false"
          :visible.sync="dialogVisible"
          width="30%"
          z-index="inherit"
          >
        <span>这是一段信息</span>
        <span slot="footer" class="dialog-footer">
           <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>

  </el-card>
</template>

<script>
import debounce from 'lodash/debounce'
import {getCategoryList} from "@/api/dish/dish";
import Cookies from "js-cookie";
import mixinViewModule from "@/mixins/view-module";
import setmealDish from './setmealdish'
export default {

  mixins: [mixinViewModule],

  components: {
    setmealDish
  },
  data () {
    return {

      mixinViewModuleOptions: {
        getDataListURL: '/demo/setmealdish/page',
        getDataListIsPage: true,
      },
      table:this.$refs.setmealDishTable.spread,
      dialogVisible: false,
      visible: false,
      url: '',
      num: 0,
      categoryList: [],
      imageUrl:'',
      dataForm: {
        id: '',
        categoryId: '',
        categoryName: '',
        name: '',
        price: '',
        status: '',
        code: '',
        description: '',
        image: '',
        setmealDishes:[],
      }
    }
  },
  computed: {
    dataRule () {
      return {
        categoryId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        price: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        status: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        description: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        image: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],

      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.url = `${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${Cookies.get('token')}`

      getCategoryList({'type': 2}).then(({data: res}) => {
        if (res.code === 0) {
          this.categoryList = res.data
        } else {
          this.$message.error(res.msg || '操作失败')
        }
      }),
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/demo/setmeal/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/demo/setmeal/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false }),


    // 上传之前
    beforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif' }))
        return false
      }
      this.num++
    },
    // 上传成功
    successHandle (res, file) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      if (this.num === 1) {
        this.imageUrl=res.data.src+res.data.fileName

        this.dataForm.image = res.data.fileName

        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,

        })
        this.num--
      }
    },

    onChange(file) {
      if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
          this.$refs.upload.clearFiles()
          return false
        }
        if (!size) {
          this.$message.error('上传文件大小不能超过 2MB!')
          return false
        }
        return file
      }
    },

  }
}
</script>
<style>

.btn-box{
  width: 180px;
  display: flex;
  justify-content: space-between;
  float: right;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>